{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #String to Integer (atoi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: myAtoi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #字符串转换整数 (atoi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>请你来实现一个&nbsp;<code>myAtoi(string s)</code>&nbsp;函数，使其能将字符串转换成一个 32 位有符号整数（类似 C/C++ 中的 <code>atoi</code> 函数）。</p>\n",
    "\n",
    "<p>函数&nbsp;<code>myAtoi(string s)</code> 的算法如下：</p>\n",
    "\n",
    "<ol>\n",
    "\t<li>读入字符串并丢弃无用的前导空格</li>\n",
    "\t<li>检查下一个字符（假设还未到字符末尾）为正还是负号，读取该字符（如果有）。 确定最终结果是负数还是正数。 如果两者都不存在，则假定结果为正。</li>\n",
    "\t<li>读入下一个字符，直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。</li>\n",
    "\t<li>将前面步骤读入的这些数字转换为整数（即，\"123\" -&gt; 123， \"0032\" -&gt; 32）。如果没有读入数字，则整数为 <code>0</code> 。必要时更改符号（从步骤 2 开始）。</li>\n",
    "\t<li>如果整数数超过 32 位有符号整数范围 <code>[−2<sup>31</sup>,&nbsp; 2<sup>31&nbsp;</sup>− 1]</code> ，需要截断这个整数，使其保持在这个范围内。具体来说，小于 <code>−2<sup>31</sup></code> 的整数应该被固定为 <code>−2<sup>31</sup></code> ，大于 <code>2<sup>31&nbsp;</sup>− 1</code> 的整数应该被固定为 <code>2<sup>31&nbsp;</sup>− 1</code> 。</li>\n",
    "\t<li>返回整数作为最终结果。</li>\n",
    "</ol>\n",
    "\n",
    "<p><strong>注意：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li>本题中的空白字符只包括空格字符 <code>' '</code> 。</li>\n",
    "\t<li>除前导空格或数字后的其余字符串外，<strong>请勿忽略</strong> 任何其他字符。</li>\n",
    "</ul>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例&nbsp;1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"42\"\n",
    "<strong>输出：</strong>42\n",
    "<strong>解释：</strong>加粗的字符串为已经读入的字符，插入符号是当前读取的字符。\n",
    "第 1 步：\"42\"（当前没有读入字符，因为没有前导空格）\n",
    "         ^\n",
    "第 2 步：\"42\"（当前没有读入字符，因为这里不存在 '-' 或者 '+'）\n",
    "         ^\n",
    "第 3 步：\"<u>42</u>\"（读入 \"42\"）\n",
    "           ^\n",
    "解析得到整数 42 。\n",
    "由于 \"42\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 42 。</pre>\n",
    "\n",
    "<p><strong>示例&nbsp;2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"   -42\"\n",
    "<strong>输出：</strong>-42\n",
    "<strong>解释：</strong>\n",
    "第 1 步：\"<u><strong>   </strong></u>-42\"（读入前导空格，但忽视掉）\n",
    "            ^\n",
    "第 2 步：\"   <u><strong>-</strong></u>42\"（读入 '-' 字符，所以结果应该是负数）\n",
    "             ^\n",
    "第 3 步：\"   <u><strong>-42</strong></u>\"（读入 \"42\"）\n",
    "               ^\n",
    "解析得到整数 -42 。\n",
    "由于 \"-42\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 -42 。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例&nbsp;3：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>s = \"4193 with words\"\n",
    "<strong>输出：</strong>4193\n",
    "<strong>解释：</strong>\n",
    "第 1 步：\"4193 with words\"（当前没有读入字符，因为没有前导空格）\n",
    "         ^\n",
    "第 2 步：\"4193 with words\"（当前没有读入字符，因为这里不存在 '-' 或者 '+'）\n",
    "         ^\n",
    "第 3 步：\"<u>4193</u> with words\"（读入 \"4193\"；由于下一个字符不是一个数字，所以读入停止）\n",
    "             ^\n",
    "解析得到整数 4193 。\n",
    "由于 \"4193\" 在范围 [-2<sup>31</sup>, 2<sup>31</sup> - 1] 内，最终结果为 4193 。\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>0 &lt;= s.length &lt;= 200</code></li>\n",
    "\t<li><code>s</code> 由英文字母（大写和小写）、数字（<code>0-9</code>）、<code>' '</code>、<code>'+'</code>、<code>'-'</code> 和 <code>'.'</code> 组成</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [string-to-integer-atoi](https://leetcode.cn/problems/string-to-integer-atoi/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [string-to-integer-atoi](https://leetcode.cn/problems/string-to-integer-atoi/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"42\"', '\"   -42\"', '\"4193 with words\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> str:\n",
    "        ans = ''\n",
    "        for c in s.strip():\n",
    "            if c in ['+', '-']:\n",
    "                if not ans:\n",
    "                    ans = ans + c\n",
    "                else:\n",
    "                    if ans in ['+', '-']:\n",
    "                        # '++', '+-', '-+', '--'\n",
    "                        return 0\n",
    "                    # -5-\n",
    "                    break\n",
    "            elif '0' <= c <= '9':\n",
    "                ans = ans + c\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        if ans in ['', '+', '-']:\n",
    "            return 0\n",
    "\n",
    "        ans = int(ans)\n",
    "        INT_MIN = -2**31\n",
    "        INT_MAX = INT_MIN * -1 - 1\n",
    "\n",
    "        if ans > INT_MAX:\n",
    "            return INT_MAX\n",
    "\n",
    "        if ans < INT_MIN:\n",
    "            return INT_MIN\n",
    "\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        num_list = []\n",
    "        isneg = 0\n",
    "        neg_flag = 0\n",
    "        blank_flag = 0\n",
    "        num_con = 0\n",
    "        y = 0\n",
    "        ground = - 2 ** 31\n",
    "        flor = -ground - 1\n",
    "        for item in str:\n",
    "            if item == \" \" and not blank_flag:\n",
    "                continue\n",
    "            elif item == \"-\" and not neg_flag and not num_con:\n",
    "                isneg = 1\n",
    "                neg_flag = 1\n",
    "                blank_flag = 1\n",
    "            elif item == \"+\" and not neg_flag and not num_con:\n",
    "                isneg = 0\n",
    "                neg_flag = 1\n",
    "                blank_flag = 1\n",
    "            elif \"0\" <= item <= \"9\":\n",
    "                num_list.append(item)\n",
    "                blank_flag = 1\n",
    "                num_con = 1\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        lens = len(num_list)\n",
    "        for i, item in enumerate(num_list):\n",
    "            y = y + int(item) * 10 ** (lens - i - 1)\n",
    "        if isneg:\n",
    "            y = -y\n",
    "        if y < ground:\n",
    "            y = ground\n",
    "        elif y > flor:\n",
    "            y = flor\n",
    "        return y\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: 'str') -> 'int':\n",
    "        n = len(str)\n",
    "        if n == 0:\n",
    "            return 0\n",
    "        i = 0\n",
    "        sign = 1\n",
    "        val = 0\n",
    "        \n",
    "        while i < n and str[i] == ' ':\n",
    "            i += 1\n",
    "            \n",
    "        if i < n and str[i] == '+':\n",
    "            sign = 1\n",
    "            i += 1\n",
    "        elif i < n and str[i] == '-':\n",
    "            sign = -1\n",
    "            i += 1\n",
    "        \n",
    "        while i < n and str[i] >= '0' and str[i] <= '9':\n",
    "            val = val * 10 + int(str[i])\n",
    "            i += 1\n",
    "        \n",
    "        val *= sign\n",
    "        if val > 2 ** 31 - 1:\n",
    "            return 2 ** 31 - 1\n",
    "        elif val < - (2 ** 31):\n",
    "            return - (2 ** 31)\n",
    "        else:\n",
    "            return val\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        import re\n",
    "        match = re.match(r'[-|+]?\\d+', str.strip())\n",
    "        if not match:\n",
    "            return 0\n",
    "        num = int(match.group())\n",
    "        if num > 2 ** 31 - 1:\n",
    "            return 2 ** 31 - 1\n",
    "        if num < - 2 ** 31:\n",
    "            return -2 ** 31\n",
    "        return num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def print_f(self, str_1):\n",
    "        if int(str_1) >= -(2 ** 31) and int(str_1) <= (2 ** 31 - 1):\n",
    "            return int(str_1)\n",
    "        elif int(str_1) < -(2 ** 31):\n",
    "            return -(2 ** 31)\n",
    "        elif int(str_1) > 2 ** 31 - 1:\n",
    "            return 2 ** 31 - 1\n",
    "            \n",
    "    def myAtoi(self, str_1):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        try:\n",
    "            return self.print_f(str_1)\n",
    "        except:\n",
    "            ans = ''\n",
    "            count = 0\n",
    "            str_1 = str_1.strip()\n",
    "            if str_1 == '':\n",
    "                return 0\n",
    "            if not str_1[0].isdigit() and str_1[0] != ' ' and str_1[0] != '+' and str_1[0] != '-' and len(ans) == 0:\n",
    "                return 0\n",
    "            while str_1[0] == '-' or str_1[0] == '+' or str_1[0].isdigit():\n",
    "                count += 1\n",
    "                ans += str_1[0]\n",
    "                if count < len(str_1):\n",
    "                    for j in str_1[count:]:\n",
    "                        if not j.isdigit() and j != 0:\n",
    "                            try:\n",
    "                                return self.print_f(ans)\n",
    "                            except:\n",
    "                                return 0\n",
    "                        else:\n",
    "                            ans += j\n",
    "                    return self.print_f(ans)\n",
    "                else:\n",
    "                    return 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        r=0\n",
    "        i=0\n",
    "        neg=1\n",
    "        if len(s)==0:#''\n",
    "            return 0\n",
    "        while i<len(s) and s[i]==' ':\n",
    "            i+=1\n",
    "        if i>=len(s):#'   '\n",
    "            return 0\n",
    "        if s[i]=='-' or s[i]=='+':\n",
    "            neg=-1 if s[i]=='-' else 1\n",
    "            i+=1\n",
    "            if i>=len(s):\n",
    "                return 0\n",
    "            # return -3\n",
    "        s=s[i:]\n",
    "        if ord(s[0])>=48 and ord(s[0])<=57:\n",
    "            j=1\n",
    "            while j<len(s) and ord(s[j])>=48 and ord(s[j])<=57:\n",
    "                j+=1\n",
    "            if j<len(s):\n",
    "                s=s[:j]\n",
    "            r = int(s)*neg\n",
    "            r=r if r>=-2147483648 and r<=2147483647 else (-2147483648 if neg<0 else 2147483647)\n",
    "            return r\n",
    "        else:\n",
    "            return 0\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        \n",
    "        result=0\n",
    "        \n",
    "        temp=list(str.strip())\n",
    "        if len(temp) == 0: return 0\n",
    "        sign=-1 if temp[0]=='-' else 1\n",
    "        if temp[0] in [\"-\", \"+\"]: del temp[0]\n",
    "        for x in temp:\n",
    "            if not x.isdigit(): break\n",
    "            result = result * 10 + ord(x) - ord(\"0\")\n",
    "            print(result)\n",
    "        \n",
    "        return max(-2**31, min(2**31-1, sign * result))\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        nums = ''\n",
    "        for i in range(len(str)):\n",
    "            if str[i] == ' ' and len(nums) == 0:\n",
    "                continue\n",
    "            elif str[i].isalpha() and len(nums) == 0:\n",
    "                return 0\n",
    "            elif str[i].isdigit():\n",
    "                nums += str[i]\n",
    "                print(str[i])\n",
    "            elif str[i] in ['-', '+'] and len(nums) == 0:\n",
    "                nums += str[i]\n",
    "                print(str[i])\n",
    "            else:\n",
    "                break\n",
    "                \n",
    "        if nums in ['', '+', '-']:\n",
    "            return 0\n",
    "        if int(nums) < -2147483648:\n",
    "            return -2147483648\n",
    "        elif int(nums) > 2147483647:\n",
    "            return 2147483647\n",
    "        return int(nums)\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import math\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        begin = -1\n",
    "        end = 0\n",
    "        number_list = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n",
    "        before_begin = \"+\"\n",
    "        for i,mark in enumerate(str):\n",
    "            print(i)\n",
    "            if begin==-1:\n",
    "                if mark in number_list:\n",
    "                    begin = i\n",
    "                elif mark not in [\" \"] and i+1<len(str) and str[i+1] not in number_list:\n",
    "                    break\n",
    "            if not begin==-1 and mark not in number_list:\n",
    "                end = i-1\n",
    "                break\n",
    "            if not begin==-1 and i == len(str)-1:\n",
    "                end = i\n",
    "        if begin>=1:\n",
    "            if str[begin-1] == \"-\":\n",
    "                begin = begin - 1\n",
    "            elif str[begin-1] not in [\"+\",\" \"]:\n",
    "                begin = -1\n",
    "        if begin == -1:\n",
    "            return 0\n",
    "        print(begin)\n",
    "        print(end)\n",
    "        print(str[begin:end+1])\n",
    "        number = int(str[begin:end+1])\n",
    "        if number > pow(2,31)-1:\n",
    "            number = pow(2,31)-1\n",
    "        elif number < -pow(2,31):\n",
    "            number = -pow(2,31)\n",
    "        print(number)\n",
    "        return number\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        num=0\n",
    "        flag=1\n",
    "       \n",
    "        i=0\n",
    "\n",
    "        # jump black   \n",
    "        str=str.lstrip()\n",
    "        print (\"-----\",str)\n",
    "\n",
    "\n",
    "        if str== '':\n",
    "            return 0\n",
    "        \n",
    "        if str[0] == '-':\n",
    "            flag = -1\n",
    "            i=1;\n",
    "        elif str[0] == '+':\n",
    "            i=1\n",
    "        \n",
    "\n",
    "        \n",
    "\n",
    "        while i<len(str) :\n",
    "            if str[i].isdigit():\n",
    "                num = num *10 + int(str[i])\n",
    "                i=i+1\n",
    "            else:\n",
    "                break\n",
    "            \n",
    "        num = num*flag\n",
    "        \n",
    "        if num > 2**31-1 :\n",
    "            num = 2**31-1\n",
    "        elif num < -2**31:\n",
    "            num = -2**31\n",
    "\n",
    "        return num\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        >>> s = Solution()\n",
    "        >>> s.myAtoi('42')\n",
    "        42\n",
    "        >>> s.myAtoi('   -42')\n",
    "        -42\n",
    "        >>> s.myAtoi('4193 with words')\n",
    "        4193\n",
    "        >>> s.myAtoi('words and 987')\n",
    "        0\n",
    "        >>> s.myAtoi('-91283472332')\n",
    "        -2147483648\n",
    "        >>> s.myAtoi('+1')\n",
    "        1\n",
    "        \"\"\"\n",
    "        num = 0\n",
    "        str = str.strip()\n",
    "        if len(str) == 0:\n",
    "            return 0\n",
    "        if str[0] == '-':\n",
    "            for i in str[1:]:\n",
    "                number =  (ord(i) - 48)\n",
    "                if number < 0 or number > 9:\n",
    "                    break \n",
    "                num = num * 10 - number\n",
    "            int_min = -1 << 31\n",
    "            if num < int_min:\n",
    "                return int_min\n",
    "            return num\n",
    "            \n",
    "        elif str[0] == '+':\n",
    "            for i in str[1:]:\n",
    "                number =  (ord(i) - 48)\n",
    "                if number < 0 or number > 9:\n",
    "                    break\n",
    "                num = num * 10 + number\n",
    "            \n",
    "            if num > ((1 << 31) - 1):\n",
    "                return (1 << 31) - 1\n",
    "            return num\n",
    "        \n",
    "        elif (ord(str[0]) >= 48 and ord(str[0]) <= 57):\n",
    "            for i in str:\n",
    "                number =  (ord(i) - 48)\n",
    "                if number < 0 or number > 9:\n",
    "                    break\n",
    "                num = num * 10 + number\n",
    "            \n",
    "            if num > ((1 << 31) - 1):\n",
    "                return (1 << 31) - 1\n",
    "            return num\n",
    "        else:\n",
    "            return 0\n",
    "\n",
    "if __name__=='__main__':\n",
    "    import doctest\n",
    "    doctest.testmod()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        nospace_str = str.strip()\n",
    "        print(nospace_str)\n",
    "        if(nospace_str == \"\"):\n",
    "            return 0\n",
    "        nospace_str = nospace_str.split()[0]\n",
    "        # 定义 有效数字集合 和 符号集合\n",
    "        num_gather = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \".\"]\n",
    "        sign_gather = [\"+\", \"-\"]\n",
    "        # 定义一个数字集合\n",
    "        gathernum = []\n",
    "        is_positive = True\n",
    "        for i in range(len(nospace_str)):\n",
    "            if nospace_str[i] in num_gather:\n",
    "                gathernum.append(nospace_str[i])\n",
    "            elif nospace_str[i] in sign_gather:\n",
    "                if i != 0:\n",
    "                    break\n",
    "                if(nospace_str[i] == \"-\"):\n",
    "                    is_positive = not is_positive\n",
    "            else:\n",
    "                break\n",
    "        if(len(gathernum) == 0):\n",
    "            return 0\n",
    "        num = int(float(\"\".join(gathernum)))\n",
    "        if(is_positive == True) and (num > 2**31 -1):\n",
    "            num = 2**31 -1\n",
    "        elif(is_positive == False):\n",
    "            num = -num\n",
    "            if(num < -2**31):\n",
    "                num = -2**31\n",
    "        return num\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        nospace_str = str.strip()\n",
    "        print(nospace_str)\n",
    "        if(nospace_str == \"\"):\n",
    "            return 0\n",
    "        nospace_str = nospace_str.split()[0]\n",
    "        # 定义一个有意义的集合\n",
    "        num_gather = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \".\"]\n",
    "        non_num_gather = [\"+\", \"-\"]\n",
    "        # 最后返回的集合\n",
    "        gathernum = []\n",
    "        is_positive = True\n",
    "        print()\n",
    "        for i in range(len(nospace_str)):\n",
    "            if nospace_str[i] in num_gather:\n",
    "                gathernum.append(nospace_str[i])\n",
    "            elif nospace_str[i] in non_num_gather:\n",
    "                if i != 0:\n",
    "                    break\n",
    "                if(nospace_str[i] == \"-\"):\n",
    "                    is_positive = not is_positive\n",
    "            else:\n",
    "                break\n",
    "        #print(int(float(\"\".join(gathernum))), gathernonnum)\n",
    "        if(len(gathernum) == 0):\n",
    "            return 0\n",
    "        #else:\n",
    "        num1 = int(float(\"\".join(gathernum)))\n",
    "        if(is_positive == True) and (num1 > 2**31 -1):\n",
    "            num1 = 2**31 -1\n",
    "        elif(is_positive == False):\n",
    "            num1 = -num1\n",
    "            if(num1 < -2**31):\n",
    "                num1 = -2**31\n",
    "        return num1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, x):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        start = -1\n",
    "        end = -1\n",
    "        for i in range(len(x)):\n",
    "            if start == -1:\n",
    "                if x[i] in [str(i) for i in range(10)]:\n",
    "                    start = i\n",
    "                    end = i + 1\n",
    "                elif x[i] == '-' or x[i] == '+':\n",
    "                    start = i\n",
    "                elif x[i] == ' ':\n",
    "                    continue\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                if not x[i] in [str(i) for i in range(10)]:\n",
    "                    end = i\n",
    "                    break\n",
    "                else:\n",
    "                    end = i+1\n",
    "        if start == -1 or end == -1:\n",
    "            member = 0\n",
    "        else:\n",
    "            member = x[start:end]\n",
    "            try:\n",
    "                member = int(member)\n",
    "            except:\n",
    "                member = 0\n",
    "\n",
    "        return min(max(-2**31,member), 2**31-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        import re\n",
    "        numList=[]\n",
    "        for line in range(10):\n",
    "            numList.append(repr(line))\n",
    "        #print(numList)\n",
    "        #s=re.split(r\"\\s+\",str)\n",
    "        s=str\n",
    "        for i in range(len(str)):\n",
    "            print(i)\n",
    "            if(str[i]==\"\\t\" or str[i]==\" \"):\n",
    "                continue\n",
    "            else:\n",
    "                s=str[i:]\n",
    "                break\n",
    "        print(s)\n",
    "        flag=False\n",
    "        slist=[]\n",
    "        if(s==\"\"or s==\"-\" or s==\"+\"):return 0\n",
    "        for i in range(len(s)):\n",
    "            if(i==0 and (s[i]=='-' or s[i]==\"+\" or s[i] in numList)):\n",
    "                slist.append(s[i])\n",
    "                continue\n",
    "            if(s[i] in numList):\n",
    "                slist.append(s[i])\n",
    "            else:break\n",
    "        ans=\"\".join(slist)\n",
    "        print(ans)\n",
    "        if(ans==\"\"or ans=='-' or ans==\"+\"):return 0\n",
    "        if(int(ans)>=2**31):\n",
    "            return  2**31-1\n",
    "        if(int(ans)<=-(2**31)):\n",
    "            return -2147483648\n",
    "        return int(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: 'str') -> 'int':\n",
    "        str = str.strip()\n",
    "        if not str:\n",
    "            return 0\n",
    "        elif str[0] == '-':\n",
    "            sig = -1\n",
    "            str = str[1:]\n",
    "        elif str[0] == '+':\n",
    "            sig = 1\n",
    "            str = str[1:]\n",
    "        else:\n",
    "            sig = 1\n",
    "        ret = 0\n",
    "        for s in str:\n",
    "            num = ord(s)\n",
    "            if num < 48 or num > 57:\n",
    "                break\n",
    "            ret *= 10\n",
    "            ret += num - 48\n",
    "        ret = ret*sig\n",
    "        if sig == 1:\n",
    "            return min(2**31-1, ret)\n",
    "        elif sig == -1:\n",
    "            return max(-1*2**31, ret)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        # 1、int(*[])=0,也就是说如果匹配不到一个字符串,将会返回0\n",
    "        # 2、^表示从它后面的表达式开始匹配\n",
    "        # 3、[\\+\\-]表示字符+或-,只取一个\n",
    "        # 4、\\d表示取一个数字\n",
    "        # 5、+代表匹配前面那个字符1到多个\n",
    "        # 6、\\d+可以表示一连串的数字\n",
    "        return max(min(int(*re.findall('^[\\+\\-]?\\d+', s.lstrip())), 2**31 - 1), -2**31)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, strs: str) -> int:\n",
    "        if not strs:\n",
    "            return 0\n",
    "        temp = list(strs)\n",
    "\n",
    "        while len(temp) > 0 and temp[0] == ' ':\n",
    "            temp.pop(0)\n",
    "\n",
    "        sign = '+'\n",
    "        if len(temp) > 0 and (temp[0] == '-' or temp[0] == '+'):\n",
    "            sign = temp[0]\n",
    "            temp.pop(0)\n",
    "        \n",
    "        num = 0\n",
    "        while len(temp) > 0 and temp[0].isdigit():\n",
    "            c = temp[0]\n",
    "            num = 10 * num + int(c)\n",
    "            temp.pop(0)\n",
    "        \n",
    "        if num != 0:\n",
    "            if sign == '-':\n",
    "                num = -1 * num\n",
    "        \n",
    "        if -1 * 2**31 > num or num > 2**31 -1 :\n",
    "            if num < 0:\n",
    "                return -1 * 2**31\n",
    "            else:\n",
    "                return 2**31 - 1\n",
    "        return num "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        return    max(min(int(*re.findall('^[\\+\\-]?\\d+',str.lstrip())),2**31-1),-2**31)\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution(object):\n",
    "    def myAtoi(self, str):\n",
    "        \"\"\"\n",
    "        :type str: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        #去掉左边字符\n",
    "        str=str.lstrip()\n",
    "        \n",
    "        #如果字符串空，返回\n",
    "        if len(str)==0:\n",
    "            return 0\n",
    "        #设置默认输出为0\n",
    "        last=0\n",
    "        #如果有符号设置起始位置2，其余的为1\n",
    "        i=2 if str[0]=='-'or str[0]=='+'  else 1\n",
    "        #循环，直到无法强转成int，跳出循环\n",
    "        while i <= len(str):\n",
    "            try:\n",
    "                last=int(str[:i])\n",
    "                i+=1\n",
    "            except:\n",
    "                break\n",
    "        #如果数字超出范围，返回范围最大值\n",
    "        if last<-2147483648 :\n",
    "            return -2147483648\n",
    "        if last>2147483647:\n",
    "            return 2147483647\n",
    "        return last\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "'''\n",
    "^：匹配字符串开头\n",
    "[\\+\\-]：代表一个+字符或-字符\n",
    "?：前面一个字符可有可无\n",
    "\\d：一个数字\n",
    "+：前面一个字符的一个或多个\n",
    "\\D：一个非数字字符\n",
    "*：前面一个字符的0个或多个\n",
    ".: 万能匹配\n",
    "'''\n",
    "# ^ 从左边最开头开始匹配\n",
    "# [\\+\\-]先匹配符号,是正号还是负号\n",
    "# ? 如果前面既没有正号也没有负号的话也可以\n",
    "# \\d 开始匹配数字\n",
    "# + 前面一个字符的一个或多个,也就是说如果前面没有+或-或数字,那就匹配失败了,因为不能有0个\n",
    "# 多个是因为有多个数字的话那就把多个数字匹配过去\n",
    "# 2^31 -  31 power of 2 ,then minus 1\n",
    "# 2 to the 31th power \n",
    "import re\n",
    "class Solution:\n",
    "    def myAtoi(self, str: str) -> int:\n",
    "        INT_MAX = 2**31 - 1    \n",
    "        INT_MIN = -2**31\n",
    "        str = str.strip()      #清除多余的空格\n",
    "        num_re = re.compile(r'^[\\+\\-]?\\d+')   #设置正则规则\n",
    "        num = num_re.findall(str)   #查找匹配的内容\n",
    "        num = int(*num) #由于返回的是个列表，解包并且转换成整数\n",
    "        return max(min(num,INT_MAX),INT_MIN)    #返回值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        # drop blanc str\n",
    "        ss = s.lstrip()\n",
    "        flag = 0\n",
    "        result = ''\n",
    "        for i in ss:\n",
    "            if i.isdigit():\n",
    "                if flag == 0:\n",
    "                    flag = 1\n",
    "                result += i\n",
    "            elif flag == 0:\n",
    "                if i == '-':\n",
    "                    flag = -1\n",
    "                elif i == '+':\n",
    "                    flag = 1\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                break\n",
    "        if len(result) < 1:\n",
    "            return 0\n",
    "\n",
    "        # judge illegal\n",
    "        int_result = int(result) * flag\n",
    "        return max( (-1)*(2**31) , min(2**31-1 , int_result) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        # drop blanc str\n",
    "        ss = s.lstrip()\n",
    "        length = len(ss)\n",
    "        flag = 0\n",
    "        result = ''\n",
    "        for i in ss:\n",
    "            if i.isdigit():\n",
    "                if flag == 0:\n",
    "                    flag = 1\n",
    "                result += i\n",
    "            elif flag == 0:\n",
    "                if i == '-':\n",
    "                    flag = -1\n",
    "                elif i == '+':\n",
    "                    flag = 1\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                break\n",
    "        if len(result) < 1:\n",
    "            return 0\n",
    "\n",
    "        # judge illegal\n",
    "        int_result = int(result) * flag\n",
    "        return max( (-1)*(2**31) , min(2**31-1 , int_result) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        # drop blanc str\n",
    "        ss = s.lstrip()\n",
    "        flag = 0\n",
    "        result = 0\n",
    "        for i in ss:\n",
    "            if i.isdigit():\n",
    "                if flag == 0:\n",
    "                    flag = 1\n",
    "                result = result*10 + int(i)\n",
    "            elif flag == 0:\n",
    "                if i == '-':\n",
    "                    flag = -1\n",
    "                elif i == '+':\n",
    "                    flag = 1\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        # judge illegal\n",
    "        int_result = int(result) * flag\n",
    "        return max( (-1)*(2**31) , min(2**31-1 , int_result) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        start = 1\n",
    "        m = -1\n",
    "        n = len(s)\n",
    "        sign = '+'\n",
    "        for i in range(len(s)):\n",
    "            if s[i] == ' ' and start:\n",
    "                continue\n",
    "\n",
    "            if start:\n",
    "                start = 0\n",
    "                if s[i] == '+' or s[i] == '-':\n",
    "                    sign = s[i]\n",
    "                    i += 1\n",
    "                    continue\n",
    "\n",
    "                if not s[i].isdigit():\n",
    "                    return 0\n",
    "\n",
    "            if s[i].isdigit():\n",
    "                if m == -1:\n",
    "                    m = i\n",
    "\n",
    "                continue\n",
    "            \n",
    "            n = i\n",
    "            break\n",
    "\n",
    "        if m == -1:\n",
    "            return 0\n",
    "        \n",
    "        print(m, n)\n",
    "        total = 0\n",
    "        for i in range(m, n):\n",
    "            total += (ord(s[i]) - ord('0')) * pow(10, n - i - 1)\n",
    "\n",
    "        limit = pow(2, 31)\n",
    "        if sign == '-':\n",
    "            total = -total\n",
    "            total = max(total, -limit)\n",
    "        else:\n",
    "            total = min(total, limit - 1)\n",
    "\n",
    "        return total\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str_: str) -> int:\n",
    "        #1.为空直接返回0\n",
    "        if not str_:\n",
    "            return 0\n",
    "        \n",
    "        #2.去除前面空格\n",
    "        str_list=list(str_)\n",
    "        while str_list:\n",
    "            if str_list[0]==\" \":\n",
    "                str_list.pop(0)\n",
    "            else:\n",
    "                break\n",
    "        str_=\"\".join(str_list)\n",
    "        print (str_)\n",
    "\n",
    "        #3.去除空格后的字符串为空返回0\n",
    "        if len(str_)==0:\n",
    "            return 0\n",
    "        \n",
    "        nums=[str(i) for i in range(10)]\n",
    "\n",
    "        #4.开始条件  判断去除空格后的第一个字符是否合法，不合法则返回0\n",
    "        if str_[0] not in nums+[\"-\",\"+\"] :\n",
    "            return 0\n",
    "        #start_i=0\n",
    "\n",
    "        #5.停止条件 连续的最后一个数字字符\n",
    "        end_i=0\n",
    "        for i in range(1,len(str_)):\n",
    "            if str_[i] in nums:\n",
    "                print (str_[i])\n",
    "                end_i=i\n",
    "            else:break\n",
    "        print (\"end_i\",end_i)\n",
    "\n",
    "        #6.如果仅仅只有一个字符，而且不是数字，是符号 那么返回0\n",
    "        if end_i==0 and str_[0] in [\"-\",\"+\"]:\n",
    "            return 0\n",
    "        #7.拿到有效数字[:end_i]   \n",
    "        num=int(str_[:end_i+1])\n",
    "\n",
    "        #8.边界条件 上下溢出时返回\n",
    "        if num>=pow(2,31):return pow(2,31)-1\n",
    "        elif num <= - pow(2,31):return  -pow(2,31)\n",
    "        #正常返回\n",
    "        else:\n",
    "            return num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, str1: str) -> int:\n",
    "        s=\"\"   #将要返回的整数字符串\n",
    "        flag=0 #为1时表示开始计数阶段，不会跳过空格\n",
    "        for i in str1:\n",
    "            print(i)\n",
    "            if str.isdigit(i):\n",
    "                s+=i\n",
    "                flag=1\n",
    "                continue\n",
    "            elif str.isalpha(i):\n",
    "                break\n",
    "            elif flag==0:\n",
    "                if i==\" \":\n",
    "                    continue\n",
    "                elif i==\"+\" or i==\"-\":\n",
    "                    s+=i\n",
    "                    flag=1\n",
    "                    continue\n",
    "            break\n",
    "        if s==\"\" or s==\"+\" or s==\"-\":\n",
    "            return 0\n",
    "        a=int(s)\n",
    "        if a>2**31-1:\n",
    "            return 2**31-1\n",
    "        elif a<-2**31:\n",
    "            return -2**31\n",
    "        else:\n",
    "            return a\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        if s != '':\n",
    "            result = []\n",
    "            start_flag = False\n",
    "            flag2 = True\n",
    "            for i in s:\n",
    "                if not start_flag:\n",
    "                    if i == ' ':\n",
    "                        continue\n",
    "                    if i == '+':\n",
    "                        start_flag = True\n",
    "                        continue\n",
    "                    if i == '-':\n",
    "                        start_flag = True\n",
    "                        flag2 = False\n",
    "                        continue\n",
    "                    if 47 < ord(i) < 58:\n",
    "                        result.append(i)\n",
    "                        start_flag = True\n",
    "                        continue\n",
    "                    else:\n",
    "                        break\n",
    "                if start_flag:\n",
    "                    if 47 < ord(i) < 58:\n",
    "                        result.append(i)\n",
    "                    else:\n",
    "                        break\n",
    "            if len(result) == 0:\n",
    "                return 0\n",
    "            while result[0] == 0:\n",
    "                del result[0]\n",
    "            sum = 0\n",
    "            weight = 1\n",
    "            for i in range(len(result)):\n",
    "                sum += int(result[len(result)-1-i])*weight\n",
    "                weight *= 10\n",
    "            if not flag2:\n",
    "                sum *= (-1)\n",
    "            if sum < (-1)*2**31:\n",
    "                return (-1)*2**31\n",
    "            elif sum > 2**31-1:\n",
    "                return 2**31-1\n",
    "            else:\n",
    "                return sum\n",
    "        else:\n",
    "            return 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        nums = str([i for i in range(10)])\n",
    "        s = s.lstrip()\n",
    "        m,k = '',''\n",
    "        if len(s) > 0 and (s[0] == '-' or s[0] == '+'):\n",
    "            m = s[0]\n",
    "            s = s[1:]\n",
    "        for j in s:\n",
    "            if j in nums and j != ' ':\n",
    "                k += j\n",
    "            else:\n",
    "                break\n",
    "        k = k.lstrip('0')\n",
    "        k = k.lstrip()\n",
    "        if k == '':\n",
    "            return 0\n",
    "        k = int(k)\n",
    "        if m == '-':\n",
    "            if k > 2**31:\n",
    "                return -2**31\n",
    "            else:\n",
    "                return -int(k)\n",
    "        elif m == '+' or m == '':\n",
    "            if k >= 2**31:\n",
    "                return 2**31-1\n",
    "            else:\n",
    "                return k\n",
    "        else:\n",
    "            return 0\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "\n",
    "        s, ans, flag = s.lstrip(), 0, 1\n",
    "        if s == \"\": return 0\n",
    "        if   s[0] == '+': s = s[1:]            \n",
    "        elif s[0] == '-': flag, s = -1, s[1:]\n",
    "        for c in s:\n",
    "            if c.isdigit(): ans = ans * 10 + int(c)\n",
    "            else: break\n",
    "        ans *= flag\n",
    "        return min(max(ans, - 1 << 31), (1 << 31) - 1)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        ans = ''\n",
    "        begin = False\n",
    "        n = len(s)\n",
    "        for i in range(n):\n",
    "            s_now = s[i]\n",
    "            if begin:\n",
    "                if(s_now.isdigit()):\n",
    "                    ans += s_now\n",
    "                else:\n",
    "                    if(len(ans)==0 or ans[-1]=='-'):\n",
    "                        return 0 \n",
    "                    break\n",
    "            elif(s_now.isdigit()):\n",
    "                ans += s_now\n",
    "                begin = True\n",
    "            elif s_now=='-':\n",
    "                ans += '-'\n",
    "                begin = True\n",
    "            elif s_now=='+':\n",
    "                begin = True\n",
    "            elif s_now !=' ':\n",
    "                return 0\n",
    "        if(ans=='' or ans=='-'):\n",
    "            return 0\n",
    "\n",
    "        ans = int(ans)\n",
    "        if(ans < -2**31):\n",
    "            ans = -2**31\n",
    "        if(ans > 2**31-1):\n",
    "            ans = 2**31-1\n",
    "        return ans\n",
    "\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from _testcapi import INT_MAX, INT_MIN\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        num = \"\"\n",
    "        for i in range(len(s)):\n",
    "            s1 = s[i]\n",
    "            if num == \"\" and \" \" == s1:\n",
    "                continue\n",
    "            elif not ('0' <= s1 <= '9') and not (\"+\" == s1 or \"-\" == s1):\n",
    "                break\n",
    "            elif num != \"\" and (\"+\" == s1 or \"-\" == s1):\n",
    "                break\n",
    "            if \"+\" == s1 or \"-\" == s1:\n",
    "                if \"+\" in num or \"-\" in num:\n",
    "                    return 0\n",
    "                num += s1\n",
    "            if '0' <= s1 <= '9':\n",
    "                num += s1\n",
    "\n",
    "        if num == \"\" or \"+\" == num or \"-\" == num:\n",
    "            return 0\n",
    "        num = int(num)\n",
    "        num = max(INT_MIN, num)\n",
    "        num = min(INT_MAX, num)\n",
    "        return num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "'''\n",
    "\n",
    "输入：s = \"   -42\"\n",
    "输出：-42\n",
    "        \n",
    "第 1 步：\"   -42\"（读入前导空格，但忽视掉）\n",
    "第 2 步：\"   -42\"（读入 '-' 字符，所以结果应该是负数）\n",
    "第 3 步：\"   -42\"（读入 \"42\"）\n",
    "解析得到整数 -42 。\n",
    "由于 \"-42\" 在范围 [-231, 231 - 1] 内，最终结果为 -42 \n",
    "\n",
    "'''\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        lens0 = len(s)\n",
    "        start_point = -1\n",
    "        end_point = -1\n",
    "        posneg = 1\n",
    "        rec = 0\n",
    "        turn0 = 0\n",
    "        num = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n",
    "\n",
    "        for index in range(lens0):\n",
    "            if turn0 == 0 and s[index] == \" \":\n",
    "                pass\n",
    "\n",
    "            elif turn0 <= 1 and rec == 0 and s[index] == \"+\":\n",
    "                rec = 1\n",
    "                turn0 = 2\n",
    "            elif turn0 <= 1 and rec == 0 and s[index] == \"-\":\n",
    "                posneg = -1\n",
    "                rec = 1\n",
    "                turn0 = 2\n",
    "\n",
    "            elif turn0 <= 2 and (s[index] in num):\n",
    "                if start_point == -1:\n",
    "                    start_point = index\n",
    "                    end_point = start_point\n",
    "                    turn0 = 2\n",
    "                else:\n",
    "                    end_point = index\n",
    "\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        \n",
    "        print(start_point,end_point,s[start_point:end_point+1])\n",
    "        \n",
    "        if start_point >= 0:\n",
    "            num_cut = posneg * int(s[start_point:end_point+1])\n",
    "            if num_cut > 2147483647:\n",
    "                num_cut = 2147483647\n",
    "            elif num_cut < -2147483648 :\n",
    "                num_cut = -2147483648\n",
    "            return num_cut\n",
    "        else:\n",
    "            return 0\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        sum = \"\"\n",
    "        flag = 1\n",
    "        s = str.lstrip(s)\n",
    "        if len(s) == 0:\n",
    "            return 0\n",
    "        else:\n",
    "            if s[0] == '-':\n",
    "                flag = 0\n",
    "                s = s[1:]\n",
    "            elif s[0] == '+':\n",
    "                flag = 1\n",
    "                s = s[1:]\n",
    "\n",
    "            i = 0\n",
    "            while i < len(s) :\n",
    "                if not str.isdigit(s[i]):\n",
    "                    break\n",
    "\n",
    "                sum = sum + s[i]\n",
    "                i += 1\n",
    "\n",
    "            if len(sum) == 0:\n",
    "                return 0\n",
    "            else:\n",
    "                if flag == 1:\n",
    "                    if int(sum) >= (pow(2,31)-1):\n",
    "                        return pow(2,31)-1\n",
    "                    else:\n",
    "                        return int(sum)\n",
    "                else:\n",
    "                    if int(sum) >= pow(2,31):\n",
    "                        return -pow(2,31)\n",
    "                    else:\n",
    "                        return -int(sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        s=s.strip()\n",
    "#        if len(s)==0:\n",
    "#            return 0\n",
    "\n",
    "        sign=1\n",
    "        if s and (s[0]=='-' or s[0]=='+'):\n",
    "#            return 0\n",
    "\n",
    "       \n",
    "#        sign=1\n",
    "            if s[0]=='-':\n",
    "                sign=-1\n",
    "            s=s[1:]\n",
    "#        elif s[0]=='+':\n",
    "#            s=s[1:]\n",
    "\n",
    "        num=0\n",
    "        for char in s:\n",
    "            if not char.isdigit():\n",
    "                break\n",
    "            num =num*10+int(char)\n",
    "        \n",
    "        num=sign*num\n",
    "        num=max(-2**31,min(num,2**31-1))\n",
    "#        if num<-2**31:\n",
    "#            return -2**31\n",
    "#        elif num>2**31-1:\n",
    "#            return 2**31-1\n",
    "#        else:\n",
    "        return num\n",
    "        \n",
    "\n",
    "solution=Solution()\n",
    "s=\"42\"\n",
    "print(solution.myAtoi(s))\n",
    "\n",
    "s=\"   -42\"\n",
    "print(solution.myAtoi(s))\n",
    "\n",
    "s=\"4319 with words\"\n",
    "print(solution.myAtoi(s))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import re\n",
    "\n",
    "class Solution:\n",
    "    def myAtoi(self, s: str) -> int:\n",
    "        a = int(*re.findall('^[-|+]?\\d+',s.lstrip()))\n",
    "        if not a:\n",
    "            return 0\n",
    "        return max(min(a,2**31 - 1), -2**31)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
